const Hapi = require('hapi');
const Plugins = require('./config/plugins');
const Config = require('./config/index');
const Routes = require('./routes');
const Models = require('./models');

const Server = new Hapi.Server({ 
    host: Config.host, 
    port: Config.port,
    routes: {
        cors: {
            origin: ['*']
        }
    }
});

const Init = async () => {
    await Server.register(Plugins);

    Routes.forEach(element => {
        Server.route(element);
    });

    Server.views({
        engines: {
            html: require('handlebars')
        },
        relativeTo: __dirname,
        path: './public/templates'
    });

    Server.state('visitor', {
        ttl: 24 * 60 * 60 * 1000 * 365 * 3,
        path: '/',
        isSecure: false,
        isHttpOnly: true,
        encoding: 'base64json',
        clearInvalid: false, // remove invalid cookies
        strictHeader: true // don't allow violations of RFC 6265
    });
    
    await Server.start();
    console.log('Server running at: ${Server.info.uri}');
};

process.on('unhandledRejection', (err) => {
    console.log(err);
    process.exit(1);
});

//Connect database
var initDb = function(){
    var sequelize = Models.sequelize;

    //Determine if the database connection is successful
     sequelize.sync({force: false}).then(function() {
        console.log("connection database successed");
     }).catch(function(err){
        console.log("connection failed due to error: %s", err);
     });    
};

Init();
initDb();